import React, { PureComponent } from 'react';
import { connect } from 'dva';
import Link from 'umi/link';
import { Form, Card, List, BackTop, Icon, Button} from 'antd';

import Ellipsis from '@/components/Ellipsis';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import TagSelect from '@/components/TagSelect';
import StandardFormRow from '@/components/StandardFormRow';

import styles from './PostList.less';

// const { Option } = Select;
const FormItem = Form.Item;
const pageSize = 15;
let pageNo = 1;
let categories = [];
let c;

@connect(({ post, loading }) => ({
  post,
  loading: loading.models.post,
  postCategoriesLoading: loading.effects['post/fetchPostCategories'],
  postLoading: loading.effects['post/fetchPost'],
}))

@Form.create({
  onValuesChange({ dispatch }, changedValues, allValues) {
    // 表单项变化时请求数据
    // eslint-disable-next-line
    console.log(changedValues, allValues);
    categories = allValues.category || [];
    // 模拟查询表单生效
    dispatch({
      type: 'post/fetchPost',
      payload: {
        category: categories,
        page: 1,
        size: pageSize,
      },
    });
  },
})

class CardList extends PureComponent {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'post/fetchPostCategories',
    });
    pageNo = 1;
    dispatch({
      type: 'post/fetchPost',
      payload: {
        page: pageNo,
        size: pageSize,
        category: c
      },
    });
  }

  fetchMore = () => {
    const { dispatch } = this.props;
    pageNo += 1;
    dispatch({
      type: 'post/appendFetchPost',
      payload: {
        page: pageNo,
        size: pageSize,
        category: categories,
      },
    });
  };

  render() {
    const {
      loading,
      form,
      post: {categories, post}, 
    } = this.props;

    const { getFieldDecorator } = form;

    c = this.props.location.query.c;

    const content = (
      <div className={styles.pageHeaderContent}>
        <p>
          说明：文章列表中所有文章均来自<a href="https://juejin.im" target="_blank">掘金</a>, 本站仅做学习使用。
        </p>
      </div>
    );

    const extraContent = (
      <div className={styles.extraImg}>
        <img
          alt="这是一个标题"
          src="https://gw.alipayobjects.com/zos/rmsportal/RzwpdLnhmvDJToTdfDPe.png"
        />
      </div>
    );

    const loadMore =
      post.length > 0 ? (
        <div style={{ textAlign: 'center', marginTop: 16 }}>
          <Button onClick={this.fetchMore} style={{ paddingLeft: 48, paddingRight: 48 }}>
            {loading ? (
              <span>
                <Icon type="loading" /> 加载中...
              </span>
            ) : (
              '加载更多'
            )}
          </Button>
        </div>
      ) : null;

    return (
      <PageHeaderWrapper title="文章列表" content={content} extraContent={extraContent}>
        <Card bordered={false}>
          <Form layout="inline">
            <StandardFormRow title="所属类目" block style={{ paddingBottom: 11 }}>
              <FormItem>
                {getFieldDecorator('category', {
                  initialValue: [c],
                })(
                  <TagSelect expandable>
                    {categories.map(ca => (
                      <TagSelect.Option key={ca.id} value={ca.id}>{ca.name}</TagSelect.Option>
                    ))}
                  </TagSelect>
                )}
              </FormItem>
            </StandardFormRow>
            {/* <StandardFormRow title="其它选项" grid last>
                <Row gutter={16}>
                  <Col xl={8} lg={10} md={12} sm={24} xs={24}>
                    <FormItem {...formItemLayout} label="活跃用户">
                      {getFieldDecorator('userId')(
                        <Select placeholder="不限" style={{ maxWidth: 200, width: '100%' }}>
                          <Option value="lisa">李三</Option>
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col xl={8} lg={10} md={12} sm={24} xs={24}>
                    <FormItem {...formItemLayout} label="好评度">
                        <Select placeholder="不限" style={{ maxWidth: 200, width: '100%' }}>
                          <Option value="good">优秀</Option>
                        </Select>
                    </FormItem>
                  </Col>
                </Row>
              </StandardFormRow> */}
          </Form>
        </Card>

        <div className={styles.cardList}>
          <List
            rowKey="id"
            style={{ marginTop: 24 }}
            loading={post.length === 0 ? loading : false}
            loadMore={loadMore}
            grid={{ gutter: 24, lg: 3, md: 2, sm: 1, xs: 1 }}
            dataSource={[...post]}
            renderItem={item =>
              item ? (
                <List.Item key={item.id}>
                  <Card hoverable className={styles.card} actions={[<a><Icon type="eye" /> ({item.viewsCount})</a>, <a><Icon type="star" /> ({item.collectionCount})</a>]}>
                    <Card.Meta
                      avatar={<Link to={`/post/user/${item.userId}`}><img alt="" className={styles.cardAvatar} src={item.user.avatarLarge} /></Link>}
                      title={<Link to={`/post/detail/${item.id}`}>{item.title}</Link>}
                      description={
                        <Ellipsis className={styles.item} lines={3}>
                          {item.summaryInfo}
                        </Ellipsis>
                      }
                    />
                  </Card>
                </List.Item>
              ) : (
                <List.Item>
                  <Button type="dashed" className={styles.newButton}>
                    <Icon type="plus" /> 新增产品
                  </Button>
                </List.Item>
              )
            }
          />
        </div>
        <BackTop />
      </PageHeaderWrapper>
    );
  }
}

export default CardList;
